/**
 * @description  : 默认显示的图片
 * @descriptionDetail : 默认显示的图片
 * @copyright    : 浙江烟草
 * @author       : mc
 * @create       : 2022-10-03 17:21:12
 */
<template>
  <view class="img-div" :style="{width:naturalWidth,height:naturalHeight}">
    <img :id="mId" :src="imgSrc" @click="clickTap" width="100%" height="100%" :alt="alt" />

    <img
      v-show="isShowDel"
      @click.stop="longTap()"
      class="img-delete"
      src="../static/case/img_del.png"
      width="10%"
    />
    <view @click.stop="chooseImg()">
      <slot name="uploadview"></slot>
    </view>
  </view>
</template>
<!--
	defaultImg: 默认显示的图片
	materialName: json 需要
	orginalData: 修改界面用，服务端拉取的数据
	seqNo: json 需要
	showPreview: 是否显示大图
	isMust:  是否必填
 -->
<script>
import util from "@/common/util.js";
export default {
  name: "s-img",
  props: {
    defaultImg: {
      type: String,
      default: ""
    },
    materialName: {
      type: String,
      default: "示例图片"
    },
    orginalData: {
      type: Object,
      default: undefined
    },
    seqNo: {
      type: String,
      default: ""
    },
    showPreview: {
      type: Boolean,
      default: false
    },
    isMust: {
      type: Boolean,
      default: true
    },
    width: {
      type: String,
      default: ""
    },
    height: {
      type: String,
      default: ""
    },
    alt: {
      type: String,
      default: ""
    },
    isDel: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      imgSrc: this.defaultImg,
      naturalWidth: "",
      naturalHeight: "",
      mId: new Date().getMilliseconds() + "",
      defaultImgSize: []
    };
  },
  computed: {
    isShowDel: function() {
      return this.isDel && this.imgSrc != this.defaultImg;
    }
  },
  watch: {
    orginalData: {
      immediate: true,
      handler(nVal) {
        if (
          nVal == undefined ||
          nVal == null ||
          nVal.applyMaterialAttArray == undefined
        ) {
          this.imgSrc = this.defaultImg;
          return;
        }
        this.imgSrc = this.$u.interface.getImgSrc(
          this.orginalData.applyMaterialAttArray[0].applyMaterialAttPath
        );
      }
    }
  },
  methods: {
    init: function() {
      util.getImgNaturalSize(this.defaultImg).then(ar => {
        this.defaultImgSize = ar;
        console.log(JSON.stringify(ar));
      });
      var img = document.getElementById(this.mId);
      if (this.width == "" && this.height == "") return;
      if (this.width == "") {
        // 设置了宽度则高度按比例计算
        if (this.height.indexOf("%") != -1) {
          this.naturalHeight = this.height;
        } else {
          this.naturalHeight = this.height + "px";
        }
      } else if (this.height == "") {
        // 设置了高度则宽度按比例
        if (this.width.indexOf("%") != -1) {
          this.naturalWidth = this.width;
        } else {
          this.naturalWidth = this.width + "px";
        }
      } else {
        if (this.height.indexOf("%") != -1) {
          this.naturalHeight = this.height;
        } else {
          this.naturalHeight = this.height + "px";
        }
        if (this.width.indexOf("%") != -1) {
          this.naturalWidth = this.width;
        } else {
          this.naturalWidth = this.width + "px";
        }
      }
    },
    longTap: function() {
      if (this.imgSrc == this.defaultImg) return;
      let self = this;
      uni.showModal({
        title: "提示",
        content: "确定要移除图片吗?",
        success: function(res) {
          if (res.confirm) {
            self.imgSrc = self.defaultImg;
            self.$emit("delListener", true);
          } else if (res.cancel) {
            console.log("用户点击取消");
            self.$emit("delListener", false);
          }
        }
      });
    },
    //选择图片
    chooseImg: function() {
      let self = this;
      // let p = document.getElementById(self.mId);
      // console.log(p.offsetHeight+'==999==='+p.offsetWidth);
      this.$api.device
        .chooseImage()
        .then(
          dat => {
            uni.showLoading({
              title: "压缩中..."
            });
            var img = new Image();
            img.src = dat;
            img.onload = function() {
              var newBase64 = ImageScale.compressImage(img, {
                // 压缩质量
                quality: 0.92,
                mime: "image/jpeg",
                // 压缩时的放大系数，默认为1，如果增大，代表图像的尺寸会变大(最大不会超过原图)
                compressScaleRatio: 1,
                // ios的iPhone下主动放大一定系数以解决分辨率过小的模糊问题
                iphoneFixedRatio: 1.5,
                // 是否采用原图像素（不会改变大小）
                isUseOriginSize: true,
                // 增加最大宽度，增加后最大不会超过这个宽度
                maxWidth: 0,
                // 使用强制的宽度，如果使用，其它宽高比系数都会失效，默认整图使用这个宽度
                forceWidth: self.defaultImgSize[0],
                // 同上，但是一般不建议设置，因为很可能会改变宽高比导致拉升，特殊场景下使用
                forceHeight: self.defaultImgSize[1]
              });
              uni.hideLoading();
              self.imgSrc = newBase64;
            };
          },
          er => {}
        )
        .catch(e => {});
    },
    clickTap: function() {
      if (!this.showPreview) return;
      if (this.imgSrc == this.defaultImg) return;
      let self = this;
      uni.previewImage({
        urls: [self.imgSrc]
      });
    },
    //获取上传图片数据,返回 null 是没有指定图片或者没变动
    getUploadData: function() {
      if (this.imgSrc == this.defaultImg) {
        if (this.isMust) {
          uni.showToast({
            title: this.materialName + "不能为空",
            icon: "none"
          });
        }
        return null;
      }
      if (this.orginalData == undefined) {
        // 新增的图片
        return {
          materialName: this.materialName,
          fileSeqNo: "" + this.seqNo,
          isFileCatalog: "1",
          applyMaterialAttArray: [
            {
              seqNo: "0",
              picName: this.materialName + ".jpg",
              applyMaterialAttPath: this.imgSrc
            }
          ]
        };
      } else {
        // 修改的图片
        var fid = "";
        if (this.imgSrc.startsWith("http")) {
          //表示没改表
          fid = this.orginalData.applyMaterialAttArray[0].applyMaterialAttPath;
        } else {
          fid = this.imgSrc;
        }
        return {
          materialName: this.materialName,
          fileSeqNo: "" + this.seqNo,
          isFileCatalog: "1",
          applyMaterialAttArray: [
            {
              seqNo: 0,
              applyMaterialAttPath: fid,
              picName: this.materialName + ".jpg"
            }
          ]
        };
      }
    }
  },
  mounted() {
    this.init();
  }
};
</script>

<style lang="scss" scoped>
.img-div {    
  position: absolute;
  top: 30px;
  left: 43px;
}
.img-delete {
  position: absolute;
  top: 10rpx;
  right: 10rpx;
  z-index: 999;
  min-width: 30rpx;
  max-width: 80rpx;
}
</style>
